<?php

App::import('Model', 'Buffer');
App::import('Model', 'Hour');
App::import('Model', 'Day');
App::import('Model', 'User');
App::import('Model', 'Account');

class FutureTweet extends AppModel {


    /**
     * Description of update
     *
     * $current_time,$userID,$String_TweetText,$accountID
     *
     * updates the fields of the array to $current_time,$userID,$String_TweetText,$accountID
     *
     * @author sherif ismail
     */
    public function update($current_time, $userID, $String_TweetText, $accountID, $status) {
        $data['FutureTweet']['tweet_text'] = $String_TweetText;
        $data['FutureTweet']['user_email'] = $userID;
        $data['FutureTweet']['status'] = $status;
        $data['FutureTweet']['release_date'] = $current_time;
        $data['FutureTweet']['account_id'] = $accountID;
        //$data['FutureTweet']['saved'] = false;
        return $data;
    }

    /**
     * Description of overlength
     *
     * @param $text
     *
     * checks if text exceede the 140 chars but if it contains a link it returns true.
     *
     * @author Sherif Ismail
     */
    function overlength($text) {
        if (strlen($text) > 140) {
            $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
            $arraytext = explode(' ', $text);
            foreach ($arraytext as $link) {
                if (preg_match($reg_exUrl, $link, $url)) {
                    return true;
                }
            }
            return false;
        } else {
            return true;
        }
    }

    /**
     * Description of deletTweet
     *
     * @param $tweetid
     *
     * deletes a tweet that not yet posted.
     *
     * @author Sherif Ismail
     */
    public function deleteTweet($user_email, $tweetID) {
        $check = $this->find('all', array('conditions' => array('FutureTweet.id' => $tweetID)));
        if ($check[0]['FutureTweet']['user_email'] == $user_email) {
            $this->delete($tweetID);
            return 'Deleted Successfully';
        } else {
            return 'You are not authorized to delete this tweet';
        }
    }

    /**
     * responsible for returning the next free time according to the buffer by getting the suitable values and then passing it to the addtobufferhelper function.
     *
     * @param: $accountID
     *
     * @author "sherif ismail"
     */
    public function addtobuffer($accountID) {
        $Buffer = new Buffer();
        $HOUR = new Hour();
        $DAY = new DAY();
        $time = date('H:i:s');
        $date = date('Y-m-d');
        $bufferID = $Buffer->find('all', array('conditions' => array('account_id' => $accountID)));
        $bufferID = $bufferID[0]['Buffer']['id'];
        $hour = $HOUR->find('all', array('conditions' => array('buffer_id' => $bufferID)));
        $day = $DAY->find('all', array('conditions' => array('buffer_id' => $bufferID)));
        $i = 0;
        while ($i < count($hour)) {
            $hours[$i] = $hour[$i]['Hour']['hour'];
            $i++;
        }
		if(count($hour)==0){
		$hours = array('0:00','6:00','12:00','18:00');
		}		
        $i = 0;
        while ($i < count($day)) {
            $days[$i] = $day[$i]['Day']['day'];
            $i++;
        }
		if(count($day)==0){
		$days = array('Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday');
		}
        array_push($days, $days[0]);
        $days[0] = '///';
        return $this->addtobufferhelper($date, $time, $hours, $days, $accountID);
    }

    /**
     * Determines the next suitable date according to the buffer
     *
     * @param: $date, $time, $hours, $days, $accountID
     *
     * @author "sherif ismail"
     */
    public function addtobufferhelper($date, $time, $hours, $days, $accountID) {
        $j = 1;
        while (true) {
            $today = date('l', strtotime($date));
            $today = substr($today,0,3);
            if (array_search($today, $days) != false) {
                $i = 0;
                while ($i < count($hours)) {
                    if ($j > 1 or strtotime($time) < strtotime($hours[$i])) {
                        if ($this->find('all', array('conditions' => array('account_id' => $accountID, 'release_date' => $date . ' ' . $hours[$i] . ':00'))) == null) {
                            return $date . ' ' . $hours[$i] . ':00';
                        }
                    }
                    $i++;
                }
            }
            $date = date('Y-m-d', strtotime("+" . $j . " days"));
            $j++;
        }
    }

    public function approve($id = NULL){
        $this->id = $id;
        $this->saveField('status','approved');
    }

    public function decline($id = NULL){
        $this->id = $id;
        $this->saveField('status','rejected');
    }


    function displayTimeline($accountID){

         $array = (array) $this->find('all', array('conditions' => array('account_id' =>$accountID)));
          return $array;

    }

    function displayBuffer($accountID , $daysArray, $hoursArray) {
        $TweetsArray = (array) $this->find('all', array('order' => array('release_date ASC'),'conditions' => array('account_id' => $accountID)));
        $result = array();
        $n = 0;
        App::uses('CakeTime', 'Utility');
        
        for($i = 0; $i<count($TweetsArray) ; $i++ )
        {
            $date = $TweetsArray[$i]['FutureTweet']['release_date'];
            $date_hour = explode(' ', $TweetsArray[$i]['FutureTweet']['release_date']);
            $hour = $date_hour[1];
            $formattedDate = CakeTime::nice($date);
            $SplittedDate = explode(',', $formattedDate);
            $day = $SplittedDate[0];
            $belongsToHours = $this->containsHour($hour, $hoursArray);
            if($this->containsDay($day, $daysArray))
            {
                if($this->containsHour($hour, $hoursArray))
                {
                    $dateOfTweet = explode(' ' , CakeTime::nice($TweetsArray[$i]['FutureTweet']['release_date']));
                    $dayOfTweet = $dateOfTweet[0].' '.$dateOfTweet[1].' '.$dateOfTweet[2];
                    $result[$n] = $TweetsArray[$i];
                    $email = $result[$n]['FutureTweet']['user_email'];
                    $result[$n]['FutureTweet']['name'] = ClassRegistry::init('User')->getFullName($email);
                    $result[$n]['FutureTweet']['day'] = $dayOfTweet;
                    $result[$n]['FutureTweet']['hour'] = $this->getHour($result[$n]['FutureTweet']['release_date']);
                    $n++;
                }
            }
                        
        }
        return $result;

    }

    function displayFilteredBuffer($date) {
        $array = (array) $this->find('all' , array('conditions' => array("AND" => array('release_date >=' => $date) , 'release_date <=' => $date.' 23:59:59')));
        return $array;
    }

    function displayFilteredPending($date) {
        $array = (array) $this->find('all' , array('conditions' => array("AND" => array('release_date >=' => $date) , 'release_date <=' => $date.' 23:59:59','status'=>'pending')));
        return $array;
    }

    public function getdate($datetime){
        $result = explode(' ', $datetime);
        return $result[0];        
    }

     function displayPending($accountID) {
        $array = (array) $this->find('all', array('conditions' => array('account_id' => $accountID,'status'=>'pending')));
        return $array;
    }
 public function getHour($date){
        $result = explode(' ', $date);
        return $result[1];   
    }

    public function containsDay($value ,$array)
    {
        for($i=0; $i<count($array); $i++)
        {
            if($value == $array[$i]['Day']['day'])
                return true;
        }
        return false;
    }
    public function containsHour($value, $array){
        for($i=0; $i<count($array); $i++)
        {
            if($value == $array[$i]['Hour']['hour'])
                return true;
        }
        return false;
    }

      /**
   * Description of postingTweet
   *
   *
   *find all tweets that have to be posted at the moment that is done by filtering the data base compering the release_date of the tweet
   *by the current time. Once the table Future_tweets is filtered with all the tweet that must be posted at the current time, the tweets will be stored
   *in an array. 
   *Before it starts posting on twitter it checks wether the tweet is already posted before or not, if it was posted it deletes it from twitter and then post it again to avoid twitter policy in repeated tweets in the same day
   *Then we call the postTweet function to post the Tweet on Twitter then we delete the tweet form the table FutureTweet.
   *To delete the tweet from the table we have to pass the id of the tweet since delete function can only take id as parameter. Therefore we need to loop on the array
   *where all tweets that should be posted now in it , and call post_to_twitter function and if the function returned true that the tweet is posted then delete it from the table
   *else keep looping until it is posted 
   *
   * @author Youssef Madkour
   */
    
    public function postingTweet() {

  $current_time = date('Y-m-d H:i:s');
        $tem = $this->getFutureTweet($current_time);
        $condition = array("FutureTweet.release_date <=" => $current_time ,"FutureTweet.status" => 'approved');    
        $length = count($tem);

     for($i= 0; $i<$length ; $i++){

          $t = $this->field('id', array("FutureTweet.release_date <=" => $current_time ,"FutureTweet.status" => 'approved'), '');
          $tweet = $this->find('first',array('conditions' => $condition));
        
          
         
          $this->post_to_twitter($tweet['FutureTweet']);
          $this->delete($t);
           
           
     // $i = count($this->find('all',array('conditions' => $condition,'fields' => array('FutureTweet.id'))));
     }

       

     }

      public function post_to_twitter($arraydata) {
        $tmpAccount = new Account();
     
        $status = ( $tmpAccount->connectionRequest($arraydata['account_id'])->post('statuses/update', array('status' => $arraydata['tweet_text'])));      
        return true;
    }


    /*
      * Description of getFutureTweet
      * @time 
      *@return the id of the tweet which should be posted  
      *get all the tweets for all the accounts that should be posted at the current time  
      *
      * @author Youssef Madkour
      */
    
    public function getFutureTweet($time = NULL ){
        
          $current_time = date('Y-m-d H:i:s');
          $condition = array("FutureTweet.release_date <=" => $current_time ,"FutureTweet.status" => 'approved');
          $tem=$this->find('all',array('conditions' => $condition,'fields' => array('FutureTweet.id')));
      
           return $tem;
    }
    
}

